package com.anycc.cloud.gateway.filter;

import com.anycc.cloud.core.util.CryptoUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * request param filter,intend to intercept password and decode it
 */
@Component
public class PasswordDecodeFilter extends ZuulFilter {
    private static final int FILTER_ORDER = 1;
    private static final boolean SHOULD_FILTER = true;
    private static final Logger logger = LoggerFactory.getLogger(PasswordDecodeFilter.class);

    @Autowired
    private CryptoUtil cryptoUtil;

    @Override
    public String filterType() {
        return FilterUtils.PRE_FILTER_TYPE;
    }

    @Override
    public int filterOrder() {
        return FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {//只拦截登录（获取token)请求
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        return request.getRequestURL().indexOf("oauth/token") != -1;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println(RequestContext.getCurrentContext().getRequest().getParameter("password"));
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Map<String, List<String>> queryParams = new HashMap<>();
        queryParams.put("username", Collections.singletonList(request.getParameter("username")));
        queryParams.put("grant_type", Collections.singletonList(request.getParameter("grant_type")));
        queryParams.put("scope", Collections.singletonList(request.getParameter("scope")));
        queryParams.put("password", Collections.singletonList(cryptoUtil.decryptJsAES(request.getParameter("password"), request.getParameter("username"))));
        ctx.setRequestQueryParams(queryParams);

        return null;
    }

}
